window.onload = function(){
    waterfall('main','box') ;
    var dataInt = {'data':[{'src':'1.jpg'},{'src':'2.jpg'},{'src':'3.jpg'},{'src':'4.jpg'},{'src':'5.jpg'},{'src':'6.jpg'},{'src':'7.jpg'}]}
    window.onscroll=function(){
        if(checkScrollSlide){
            var oParent = document.getElementById('main') ;
            for(var i = 0 ; i < dataInt.data.length ; i++){
                var oBox = document.createElement('div') ;
                oBox.className = 'box' ;
                oParent.appendChild(oBox) ;
                var oPic = document.createElement('div') ;
                oPic.className = 'pic' ;
                oBox.appendChild(oPic) ;
                var oImg = document.createElement('img') ;
                oImg.src = 'img/'+dataInt.data[i].src ;
                oPic.appendChild(oImg) ;
            }
        }
        waterfall('main','box') ;
    }
}

function waterfall(parent,box){
    //将main下所有class为box的元素取出来
    var oParent = document.getElementById(parent) ;
    var oBoxs = getByClass(oParent,box) ;

    //计算整个页面显示的列数（页面宽/box的宽）
    var oBoxW = oBoxs[0].offsetWidth ;
    var cols = Math.floor(document.documentElement.clientWidth/oBoxW) ;
    console.log(cols) ;

    //设置main的宽度
    oParent.style.cssText = 'width:'+oBoxW*cols +'px;margin:auto' ;

    var hArr = [] ;//存放每列高度的数组
    for(var i =0; i<oBoxs.length;i++){
        if (i<cols){
            hArr.push(oBoxs[i].offsetHeight) ;
        }else{
            var minH = Math.min.apply(null,hArr) ;
            var index = getMinhIndex(hArr,minH) ;
            console.log('index:'+index)
            oBoxs[i].style.position = 'absolute' ;
            oBoxs[i].style.top = minH + 'px' ;
            // oBoxs[i].style.left = oBoxW*index + 'px' ; //获取左侧宽度方法1
            oBoxs[i].style.left = oBoxs[index].offsetLeft+'px';
            hArr[index] += oBoxs[i].offsetHeight;//改变数组

        }
    }
   console.log(hArr+"*"+minH) ;




}

//
function getMinhIndex(arr,value){
    for(var i in arr){
       if(arr[i] == value){
           return i ;
       }
    }
}

//根据class获取元素
function getByClass(parent,clsName){
  var boxArr = [] ,//用来存储获取到的所有class为box的元素
      oElements = parent.getElementsByTagName("*") ;
  for(var i = 0 ; i< oElements.length;i++){
      if(oElements[i].className == clsName){
          boxArr.push(oElements[i]) ;
      }
  }

  return boxArr ;
}


//检测是否加载数据块的条件
function checkScrollSlide(){
    var oParent = document.getElementById('main') ;
    var oBox = getByClass(oParent,'box') ;
    var lastBoxH = oBox[oBox.length-1].offsetTop+Math.floor(oBox[oBox.length-1].offsetHeight/2)
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop ;
    var height = document.body.clientHeight || document.documentElement.clientHeight ;
    return (lastBoxH<scrollTop+height)?true:false ;
}


